package sdu.icat.pj.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import sdu.icat.pj.base.ResponseMap;
import sdu.icat.pj.service.SysUserService;
import sdu.icat.pj.util.MD5Util;
import sdu.icat.pj.util.TokenUtil;
import sdu.icat.sys.smodel.SysUser;

@RestController
@RequestMapping("pc_client")
@Api(value="pc login",tags={"login"})
public class LoginController {

    private final Logger logger = LogManager.getLogger();

    @Autowired private SysUserService sysUserService;

    @PostMapping("login.api")
    @ApiOperation(value="会员登陆", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String,Object> login(String username,String password,String url,HttpServletRequest request, HttpServletResponse response) {
	//	String uuid = request.getHeader("UUID");
	//	Assert.notNull(uuid, "非法操作");
	
	Assert.notNull(username,"ACCOUNT");
	Assert.notNull(password, "PASSWORD");
	Subject subject = SecurityUtils.getSubject();
	SysUser user = sysUserService.queryOne(username);
	Map<String,Object> params = new HashMap<>();
	params.put("countSql", 0);
	params.put("enable", 1);
	params.put("loginKey", user.getAccount());//登录账号/手机号/邮箱
	String pwd = MD5Util.getMD5Password(user.getAccount(), password);
	UsernamePasswordToken token = TokenUtil.getTokenInfo(username, pwd);
	if(!subject.isAuthenticated()) {
	    subject.login(token);
	    logger.info("{} 通过了登录验证",username);
	    params.put("status", 200);
	    params.put("target", url+"?token="+subject.getSession().getId());
	    params.put("msg", "login success!");
	    return params;
	} else {
	    Map<String,Object> result = new HashMap<>();
	    result.put("status", -1);
	    result.put("msg", "login failed");
	    return result;
	}
    }

    @PostMapping("logout.api")
    @ApiOperation(value="登出",produces=MediaType.APPLICATION_JSON_VALUE)
    public Map<String,Object> logout(HttpServletRequest request) {
	return TokenUtil.delToken();
    }

    @PostMapping("chkAccount.api")
    @ApiOperation(value="检查手机号/账号/邮箱是否存在",produces=MediaType.APPLICATION_JSON_VALUE)
    public Map<String,Object> chkAccount(String ticket,HttpServletRequest request,HttpServletResponse response) {
	SysUser user = sysUserService.queryOne(ticket);
	Map<String,Object> result = new HashMap<>();
	result.put("exist", false);
	if(user!=null) {
	    result.put("loginKey", user.getAccount());
	    result.put("exist", true);
	    result.put("msg", "该用户已存在，不能用来注册");
	} else {
	    result.put("loginKey", ticket);
	    result.put("msg", "该用户不存在，可以用来注册");
	}
	return result;
    }

    @GetMapping("/first")
    @ApiOperation("第一个请求")
    public ResponseMap firstRes(HttpServletRequest request) {
	ResponseMap result = ResponseMap.newInstance();
	request.getSession().setAttribute("request Url", request.getRequestURL());  
	return result.setAttribute("requestUrl", request.getRequestURL());
    }

    @GetMapping("/session")
    @ApiOperation("获取会话")
    public ResponseMap sessions(HttpServletRequest request) {
	ResponseMap result = ResponseMap.newInstance();
	return result.setAttribute("sessionId", request.getSession().getId())
		.setAttribute("message", request.getSession().getAttribute("map"));
    } 


}
